package org.sfans.common.security;

import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;

public class CipherTools {

	private static final String CHARSET_NAME = "UTF-8";

	public static String initKey(final String key) {
		try {
			return DESCoder.initKey(key);
		} catch (Exception e) {
			throw new RuntimeException("CipherTools:initKey error", e);
		}
	}

	private static String encoding(final byte[] bytes) throws Exception {
		return Base32.encode(bytes);
	}

	private static byte[] decoding(final String value) throws Exception {
		return Base32.decode(value);
	}

	private static byte[] encrypt(final String key, final byte[] data) throws Exception {
		return DESCoder.encrypt(data, key);
	}

	public static String encrypt(final String value, final String key) {
		try {
			byte[] data;
			if (!StringUtils.isEmpty(CHARSET_NAME)) {
				try {
					data = value.getBytes(CHARSET_NAME);
				} catch (Exception e1) {
					data = value.getBytes();
				}
			} else {
				data = value.getBytes();
			}
			byte[] bytes = encrypt(key, data);
			return encoding(bytes);
		} catch (Exception e) {
			return null;
		}
	}

	private static byte[] decrypt(final String key, final byte[] data) throws Exception {
		return DESCoder.decrypt(data, key);
	}

	public static String decrypt(final String value, final String key) {
		try {
			byte[] data = decoding(value);
			byte[] bytes = decrypt(key, data);
			if (!StringUtils.isEmpty(CHARSET_NAME)) {
				try {
					return new String(bytes, CHARSET_NAME);
				} catch (UnsupportedEncodingException e1) {
					return new String(bytes);
				}
			} else {
				return new String(bytes);
			}
		} catch (Exception e) {
			return null;
		}
	}

}
